package com.xiaozheng.utils;

import java.sql.SQLException;

/**
 * @Package: com.xiaozheng.utils
 * @ClassName: TransactionManger
 * @Author: 小政同学    QQ:xiaozheng666888@qq.com
 * @CreateTime: 2020/9/27 13:28
 * @What_is_this_file_for: 和事务管理相关的工具类
 * @Description: 包含了开启事务，提交事务，回滚事务和释放连接
 */
public class TransactionManger {

    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /**
     * 开启事务
     */
    public void begin() {
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit() {
        try {
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public void rollback() {
        try {
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 释放连接
     */
    public void release() {
        try {
            //换回连接池
            connectionUtils.getThreadConnection().close();
            // 调用removConnection解绑
            connectionUtils.removeConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}
